package com.yinhai.ta404.core.utils;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import javax.naming.InitialContext;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Pattern;
import com.yinhai.ta404.module.security.cas.utils.ServerDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetUtils {
    private static final String LOCALHOST = "127.0.0.1";
    private static final String ANYHOST = "0.0.0.0";
    private static final int MIN_PORT = 0;
    private static final int MAX_PORT = 65535;
    private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
    private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    private static int PORT = 0;
    private static int HTTP_PORT = 0;
    private static int HTTPS_PORT = 0;
    private static volatile InetAddress LOCAL_ADDRESS = null;

    private static final Logger LOGGER = LoggerFactory.getLogger(NetUtils.class);

    public NetUtils() {

    }

    public static boolean isInvalidPort(int port) {
        return port > MIN_PORT && port <= MAX_PORT;
    }

    public static boolean isValidAddress(String address) {
        return ADDRESS_PATTERN.matcher(address).matches();
    }

    public static int getServerPort() {
        if (PORT != 0) {
            return PORT;
        } else {
            try {
                MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                ObjectName rt;
                String scheme;
                if (ServerDetector.isTomcat()) {
                    Set<ObjectName> objs = server.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
                    Iterator var2 = objs.iterator();

                    while (var2.hasNext()) {
                        rt = (ObjectName) var2.next();
                        scheme = server.getAttribute(rt, "scheme").toString();
                        String port = rt.getKeyProperty("port");
                        if ("https".equals(scheme)) {
                            HTTPS_PORT = Integer.parseInt(port);
                        } else if ("http".equals(scheme)) {
                            HTTP_PORT = Integer.parseInt(port);
                        }
                    }
                } else {
                    ObjectName service;
                    if (ServerDetector.isWebLogic()) {
                        service = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
                        InitialContext ctx = new InitialContext();
                        server = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
                        if (server == null) {
                            server = (MBeanServer) ctx.lookup("java:comp/jmx/runtime");
                        }

                        rt = (ObjectName) server.getAttribute(service, "ServerRuntime");
                        HTTP_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt, "ListenPort")));
                        scheme = String.valueOf(server.getAttribute(rt, "SSLListenPortEnabled"));
                        if ("true".equals(scheme)) {
                            HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(rt, "SSLListenPort")));
                        }
                    } else if (ServerDetector.isJBoss()) {
                        try {
                            service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=https");
                            HTTPS_PORT = Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
                        } catch (Exception var6) {
                        }

                        service = new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http");
                        HTTP_PORT = Integer.parseInt(String.valueOf(server.getAttribute(service, "port")));
                    } else {
                        System.out.println("Unsupport auto detect " + ServerDetector.getServerId() + " server port！Please set the rest port manually!");
                    }
                }
            } catch (Exception var7) {
                System.out.println("Get application server  port fail! Please make sure that application server`s JMX is enabled!");
            }

            if (HTTPS_PORT != 0) {
                PORT = HTTPS_PORT;
            } else {
                PORT = HTTP_PORT;
            }

            return PORT;
        }
    }

    public static boolean isLocalHost(String host) {
        return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || "localhost".equalsIgnoreCase(host));
    }

    public static boolean isAnyHost(String host) {
        return ANYHOST.equals(host);
    }

    public static boolean isInvalidLocalHost(String host) {
        return host == null || host.length() == 0 || "localhost".equalsIgnoreCase(host) || ANYHOST.equals(host) || LOCAL_IP_PATTERN.matcher(host).matches();
    }

    public static boolean isValidLocalHost(String host) {
        return !isInvalidLocalHost(host);
    }

    public static InetSocketAddress getLocalSocketAddress(String host, int port) {
        return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
    }

    private static boolean isValidAddress(InetAddress address) {
        if (address != null && !address.isLoopbackAddress()) {
            String name = address.getHostAddress();
            return name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches();
        } else {
            return false;
        }
    }

    public static String getLocalHost() {
        String host = System.getProperty("dubbo.protocol.host");
        if (host != null && !"".equals(host)) {
            LOGGER.debug("return local host: {}", host);
            return host;
        } else {
            InetAddress address = getLocalAddress();
            LOGGER.debug("return local host: {}", address == null ? LOCALHOST : address.getHostAddress());
            return address == null ? LOCALHOST : address.getHostAddress();
        }
    }

    public static InetAddress getLocalAddress() {
        if (LOCAL_ADDRESS != null) {
            return LOCAL_ADDRESS;
        } else {
            InetAddress localAddress = getLocalAddress0();
            LOCAL_ADDRESS = localAddress;
            return localAddress;
        }
    }

    public static InetAddress getLocalInetAddress() {
        try {
            Enumeration enu = NetworkInterface.getNetworkInterfaces();

            while (enu.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) enu.nextElement();
                if (!ni.isLoopback()) {
                    Enumeration addressEnumeration = ni.getInetAddresses();

                    while (addressEnumeration.hasMoreElements()) {
                        InetAddress address = (InetAddress) addressEnumeration.nextElement();
                        if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && !address.isAnyLocalAddress()) {
                            return address;
                        }
                    }
                }
            }
        } catch (SocketException var4) {
            var4.printStackTrace();
            return null;
        }
        System.out.println("No validated local address!");
        return null;
    }

    private static InetAddress getLocalAddress0() {
        InetAddress localAddress = null;

        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                LOGGER.debug("local host1: {}", localAddress.getHostAddress());
                return localAddress;
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = (NetworkInterface) interfaces.nextElement();
                        Enumeration addresses = network.getInetAddresses();
                        if(network.getName() != null){
                            if(network.getName().startsWith("eth") || network.getName().startsWith("en")
                                    || network.getName().startsWith("wl") || network.getName().startsWith("ww")){
                                while (addresses.hasMoreElements()) {
                                    try {
                                        InetAddress address = (InetAddress) addresses.nextElement();
                                        if (isValidAddress(address)) {
                                            if (address instanceof Inet6Address) {
                                                continue;
                                            }
                                            LOGGER.debug("local host2: {}", address.getHostAddress());
                                            return address;
                                        }
                                    } catch (Exception var5) {
                                        var5.printStackTrace();
                                    }
                                }
                            }
                        }

                    } catch (Exception var6) {
                        var6.printStackTrace();
                    }
                }
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        System.out.println("Could not get local host ip address, will use 127.0.0.1 instead.");

        return localAddress;
    }

    public static String getHostName(String address) {
        try {
            int i = address.indexOf(58);
            if (i > -1) {
                address = address.substring(0, i);
            }

            InetAddress inetAddress = InetAddress.getByName(address);
            if (inetAddress != null) {
                return inetAddress.getHostName();
            }
        } catch (Exception var3) {
        }

        return address;
    }

    public static String getIpByHost(String hostName) {
        try {
            return InetAddress.getByName(hostName).getHostAddress();
        } catch (UnknownHostException var2) {
            return hostName;
        }
    }

    public static String toAddressString(InetSocketAddress address) {
        return address.getAddress().getHostAddress() + ":" + address.getPort();
    }

    public static InetSocketAddress toAddress(String address) {
        int i = address.indexOf(58);
        String host;
        int port;
        if (i > -1) {
            host = address.substring(0, i);
            port = Integer.parseInt(address.substring(i + 1));
        } else {
            host = address;
            port = 0;
        }

        return new InetSocketAddress(host, port);
    }

}
